
package com.xinzhidi.web.ctw.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinzhidi.common.constant.AgreementConstants;
import com.xinzhidi.common.core.controller.BaseController;
import com.xinzhidi.common.core.domain.AjaxResult;
import com.xinzhidi.common.utils.SecurityUtils;
import com.xinzhidi.web.ctw.domain.entity.HouseholdTemperature;
import com.xinzhidi.web.ctw.domain.entity.HouseholdTemperatureHistory;
import com.xinzhidi.web.ctw.service.CtwService;
import com.xinzhidi.web.ctw.service.HouseholdTemperatureHistoryService;
import com.xinzhidi.web.ctw.service.HouseholdTemperatureService;
import com.xinzhidi.web.equipment.domain.Equipment;
import com.xinzhidi.web.equipment.service.EquipmentService;
import com.xinzhidi.web.house.domain.Household;
import com.xinzhidi.web.house.service.IHouseholdService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName CtwController
 * @Description: ctw管理控制器
 * @Author cx
 * @Date 2023-05-23 00:03
 * @Version V1.0
 **/
@Api(value = "ctw接口")
@RestController
@RequestMapping("/ctw")
@RequiredArgsConstructor
@Slf4j
public class CtwController extends BaseController {


    private final CtwService ctwService;

    private final HouseholdTemperatureService temperatureService;

    private final HouseholdTemperatureHistoryService historyService;

    private final IHouseholdService householdService;

    private final EquipmentService equipmentService;

    @ApiOperation("下发指令")
    @GetMapping("/sendOrder")
    public AjaxResult sendOrder(String deviceId, Integer uploadCycle, Integer Temperature) {
        return AjaxResult.success(ctwService.sendOrder(deviceId, SecurityUtils.getUserId(), uploadCycle, Temperature));
    }

    @PostMapping("/receive")
    public Map<String, Object> propertyPush() {
        log.info("CTWing订阅消息推送");
        HashMap<String, Object> map = new HashMap<>();
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes == null) {
                map.put("http", 500);
                return map;
            }
            HttpServletRequest request = requestAttributes.getRequest();
            StringBuilder buffer = new StringBuilder();
            InputStream is = request.getInputStream();
            InputStreamReader reader = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(reader);
            String s = "";
            while ((s = br.readLine()) != null) {
                buffer.append(s);
            }
            String Result = buffer.toString();
            JSONObject jsonObject = JSON.parseObject(Result);
            System.out.println("接收推送数据是:" + Result);
            if (!jsonObject.get("messageType").equals("dataReport")) {
                return null;
            }
            String deviceId = jsonObject.get("deviceId").toString();
            Long timestamp = jsonObject.getLong("timestamp");
            //根据设备id查询室温采集器设备信息
            LambdaQueryWrapper<Equipment> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(Equipment::getProtocolType, AgreementConstants.AgreementType.GREENHOUSE_COLLECTOR);
            wrapper.eq(Equipment::getAddress, deviceId);
            wrapper.eq(Equipment::getEquipmentType, AgreementConstants.EquipmentType.TEMPERATURE_COLLECTOR);
            Equipment equipment = equipmentService.getOne(wrapper);
            if (equipment == null) {
                return null;
            }
            equipment.setStatus(1);
            equipment.setUpdateTime(new Date());
            equipmentService.updateById(equipment);
            //获取住户
            Household household = householdService.getById(equipment.getHouseholdId());
            if (household == null) {
                return null;
            }

            String appData = (JSON.parseObject(jsonObject.get("payload").toString())).get("APPdata").toString();
            byte[] decodedBytes = Base64.getDecoder().decode(appData);
            String decodedString = new String(decodedBytes);

            //真实室温
            BigDecimal trueTemperature = new BigDecimal(decodedString.split(",")[0]).divide(new BigDecimal(100));

            //修正室温
            BigDecimal modifiedTemperature = new BigDecimal(decodedString.split(",")[1]).divide(new BigDecimal(100));

            //用户设定温度
            BigDecimal setTemperature = new BigDecimal(decodedString.split(",")[2]).divide(new BigDecimal(100));

            //信号强度
            Integer signalStrength = Integer.valueOf(decodedString.split(",")[3]);


            //查询是否已存在实时数据
            //修改住户室温实时数据
            LambdaQueryWrapper<HouseholdTemperature> temperatureWrapper = Wrappers.lambdaQuery();
            temperatureWrapper.eq(HouseholdTemperature::getHouseholdId, equipment.getHouseholdId());
            HouseholdTemperature householdTemperature = temperatureService.getOne(temperatureWrapper);

            BigDecimal oldTrueTemperature = null;
            if (householdTemperature == null) {
                householdTemperature = new HouseholdTemperature();
                householdTemperature.setPlotId(equipment.getLotId());
                householdTemperature.setBuildId(equipment.getBuildId());
                householdTemperature.setUnitId(equipment.getUnitId());
                householdTemperature.setHouseholdId(equipment.getHouseholdId());
                householdTemperature.setDeviceId(deviceId);
                householdTemperature.setTemperature(trueTemperature);
                householdTemperature.setModifiedTemperature(modifiedTemperature);
                householdTemperature.setSetTemperature(setTemperature);
                householdTemperature.setSignalStrength(signalStrength);
                householdTemperature.setReportTime(new Date(timestamp));
                temperatureService.save(householdTemperature);
            } else {
                oldTrueTemperature = householdTemperature.getTemperature();
                householdTemperature.setTemperature(trueTemperature);
                householdTemperature.setReportTime(new Date(timestamp));
                temperatureService.updateById(householdTemperature);
            }

            LambdaQueryWrapper<HouseholdTemperatureHistory> historyWrapper = Wrappers.lambdaQuery();
            historyWrapper.eq(HouseholdTemperatureHistory::getDeviceId, deviceId)
                    .eq(HouseholdTemperatureHistory::getReportTime, new Date(timestamp));

            HouseholdTemperatureHistory history = historyService.getOne(historyWrapper);
            if (history == null) {
                HouseholdTemperatureHistory temperatureHistory = new HouseholdTemperatureHistory();
                temperatureHistory.setPlotId(equipment.getLotId());
                temperatureHistory.setBuildId(equipment.getBuildId());
                temperatureHistory.setUnitId(equipment.getUnitId());
                temperatureHistory.setHouseholdId(equipment.getHouseholdId());
                temperatureHistory.setDeviceId(deviceId);
                temperatureHistory.setTemperature(trueTemperature);
                temperatureHistory.setModifiedTemperature(modifiedTemperature);
                temperatureHistory.setSetTemperature(setTemperature);
                temperatureHistory.setSignalStrength(signalStrength);
                temperatureHistory.setReportTime(new Date(timestamp));
                historyService.save(temperatureHistory);
            }
            //检查是否超限异常及波动异常
            temperatureService.checkTransfiniteException(equipment, oldTrueTemperature, trueTemperature);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        map.put("http", 200);
        return map;
    }

}
